const app = getApp()
import { CategoryModel } from '../../models/CategoryModel.js'
let category = new CategoryModel()
const UTIL = require('../../utils/util');
import { base64src } from '../../utils/base64src.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    zhiliang:['晚点包赔','坏单可赔','买贵赔'],
    current: 0,//轮播显示数量
    pics:[
        '../../image/iamg-doujiao.png',
        '../../image/nologin.png',
        '../../image/gouwu_kong.png'
    ],
    detail:[],//商品数据
    Hei:'',//图片高度

    is_share_html:true,
    evalatImage:'',//商品图
    bgBanner:'',
    imagePath:"",//保存图片
    maskHidden:false,
    qrcode_image:''//获取二维码
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let that = this
    // let id = "SC101"
    that.commodityPost(options.id); //商品详情数据
    // that.commodityPost(id); //商品详情数据

    //获取商品图片网上路径信息(需将BASE64转为本地图片)
    that.qrcode_image(data =>{
      base64src(data, res => {
        console.log(res)
        that.setData({
          qrcode_image: res
        })
      });
    });
    //背景图
    wx.cloud.getTempFileURL({
      fileList: ['cloud://yun-duan-8693e.7975-yun-duan-8693e-1302866574/image/20200331125904378.jpg'],
      success: res => {
        console.log(res.fileList[0].tempFileURL)
        let imgUrl = res.fileList[0].tempFileURL
        wx.getImageInfo({
          src: imgUrl,
          success: function (res) {
            that.setData({
              bgBanner:res.path
            })
          }
        })
      },
      fail: console.error
    })
  },
  getTempFileURL:function(callBack){
    let that = this
    let data = that.data.detail.thumb[that.data.current]
    //获取商品图片网上路径信息
    wx.cloud.getTempFileURL({
      fileList: [data],
      success: res => {
        console.log(res.fileList[0].tempFileURL)
        let imgUrl = res.fileList[0].tempFileURL
        wx.getImageInfo({
          src: imgUrl,
          success: function (res) {
            console.log(res)
            callBack(res)
            that.setData({
              evalatImage:res.path
            })
          }
        })
      },
      fail: console.error
    })
  },
  //查询商品详情数据
  commodityPost:function(goodsid){
    category.getDetailProduct(goodsid, data => {
      console.log(data)
      let res = data.result.data.list[0]
      console.log(res)
      let carts = wx.getStorageSync('carts') || [] //获取缓存中carts信息
      carts.forEach(v => {
        if(v._id == res._id){
          res.num = v.num
        }
      })
      this.setData({
        detail:res,
        title:res.name
      })
    })
  },
  //添加购物车
  addShopCar(e) {
    console.log(e)
    let that = this
    let detail = that.data.detail
    detail.thumb = detail.thumb[0]
    delete detail.title 
    detail.num += 1;
    //缓存购物车数据
    let carts = wx.getStorageSync('carts') || []
    if(carts.length == 0){
      carts.push(detail);
    }else{
      let hasInfo = this._checkProduct(detail._id, carts)
      if(hasInfo.index == -1){
        carts.push(detail);
      }else if(hasInfo.index != -1){
        carts[hasInfo.index].num = detail.num
      }
    }
    wx.setStorageSync('carts',carts)
    that.setData({
      'detail.num': detail.num
    })
    console.log(detail)
    if (!detail) {
      return
    }
    //库存
    if (detail.stock <= 0) {
      wx.showToast({
        title: '已售罄~',
        icon: 'none'
      })
      return
    }
    category.addCart(detail, data => {
      console.log(data)
      if(data.errMsg == "cloud.callFunction:ok"){
          wx.showToast({
            title: '已添加',
            icon: 'success'
          })
      }
    })
  },
  /*购物车中是否已经存在该商品*/
  _checkProduct(id, arr) {
    let item, result = { index: -1 };
    for (let i = 0; i < arr.length; i++) {
        item = arr[i];
        if (item._id == id) {
            result = {
                index: i,
                data: item
            }
            break;
        }
    }
    return result;
  },
  //轮播数量显示
  swiperChange: function(e) {
    if (e.detail.source == 'touch') {
      this.setData({
        current: e.detail.current
      })
    }
  },
  //轮播图片高度自适应
  imgH:function(e){
    let winWid = wx.getSystemInfoSync().windowWidth;//获取当前屏幕的宽度
    let imgh=e.detail.height;//图片高度
    let imgw=e.detail.width;
    let swiperH=winWid*imgh/imgw + "px"//等比设置swiper的高度。  即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度    ==》swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
        Hei:swiperH//设置高度
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  //扫描购物车统计购物车的数量
  scanCarts:function(products){
    let that = this;   
    let carts = wx.getStorageSync('carts') //获取缓存中carts信息
    console.log(products)
    console.log(carts)
    // for(var i = 0;i<products.length-1;i++){
    //   products[i].num = 0
    //   for(var j = 0;j<carts.length;j++){
    //     if(products[i]._id == carts[j]._id){
    //       products[i].num = carts[j].num
    //     }
    //   }
    // }
    // that.setData({
    //   'detail':this.data.products
    //  })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var  that = this;
    
  },
 //点击生成海报
 formSubmit: function (e) {
  var that = this;
  that.getTempFileURL(res=>{
    console.log(res)
    that.createNewImg(res.path);
  })
  wx.showToast({
    title: '海报生成中...',
    icon: 'loading',
    duration: 1000
  });

  setTimeout(function () {
    wx.hideToast()
    that.setData({
      maskHidden: true
    });
  }, 1000);
},
//将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
createNewImg: function (evalatImage) {
  let that = this;
  console.log(evalatImage)
  let context = wx.createCanvasContext('mycanvas');
  context.clearRect(0, 0, 375, 660);
  // context.setFillStyle("#fff")
  // context.fillRect(0, 0, 375, 660)
  context.save();

  //背景图
  let path1 = that.data.bgBanner;
  context.drawImage(path1, 0, 0, 375, 660);
  context.save();

  //商品图
  context.drawImage(evalatImage, 62.5, 0, 250, 250);
  context.save();

  //商品名称
  let title = that.data.title;
  context.setFontSize(25);
  const grd = context.createLinearGradient(30, 10, 120, 10)
  grd.addColorStop(0,"#223a65");
  grd.addColorStop(0.5,"#656a45");
  grd.addColorStop(1.0,"#c496cf");
  context.setStrokeStyle(grd);
  context.strokeText(title,10,50);
  context.stroke();
  context.save();

  //二维码
  let path2 = that.data.qrcode_image;
  context.beginPath();
  context.arc(50, 610, 50, 0, 2 * Math.PI);
  context.clip(); //裁剪上面的圆形
  context.drawImage(path2, 0, 560, 100, 100);

  context.save(); //保存之前的画布设置
  context.draw(true);//true表示保留之前绘制内容

  //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
  setTimeout(function () {
    wx.canvasToTempFilePath({
      canvasId: 'mycanvas',
      success: function (res) {
        let tempFilePath = res.tempFilePath;
        console.log(tempFilePath)
        that.setData({
          imagePath: tempFilePath
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  }, 1000);
},

//点击保存到相册
baocun: function () {
  var that = this
  wx.saveImageToPhotosAlbum({
    filePath: that.data.imagePath,
    success(res) {
      wx.showModal({
        content: '图片已保存到相册，赶紧晒一下吧~',
        showCancel: false,
        confirmText: '好的',
        confirmColor: '#333',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            /* 该隐藏的隐藏 */
            that.setData({
              maskHidden: false
            })
          }
        }, fail: function (res) {
          console.log(11111)
        }
      })
    }
  })
},
//获取二维码
qrcode_image: function (callBack) {
  let that = this;
  wx.cloud.callFunction({
    name: 'qr_code',
    data: {},
    success: function(res) {
      console.log(res) // 3
      let qrcode_image = res.result.buffer
      let bin64 = wx.arrayBufferToBase64(qrcode_image);
      callBack("data:image/jpg;base64," + bin64)
    },
    fail: console.error
  })
},
// 显示和隐藏
share_handler: function() {
  this.setData({
    is_share_html: false
  })
},
hide_share_handler: function() {
  this.setData({
    is_share_html: true
  })
},
jump_shop:function(){
  console.log('进入')
  wx.switchTab({
    url: '../shopcart/shopcart'
  })
},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})